
package com.jf.cloud.service.sysmanager.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jf.cloud.service.sysmanager.common.base.BaseService;
import com.jf.cloud.service.sysmanager.common.base.GenericsUtils;
import com.jf.cloud.service.sysmanager.common.base.OPaging;
import com.jf.cloud.service.sysmanager.common.db.BaseDao;
import com.jf.cloud.service.sysmanager.common.db.Condition;
import com.jf.cloud.service.sysmanager.common.taglib.Paging;
import com.jf.cloud.service.sysmanager.common.util.DateUtil;
import com.jf.cloud.service.sysmanager.common.util.SequenceHandler;
import com.jf.cloud.service.sysmanager.constant.PubgConstant;
import com.jf.cloud.service.sysmanager.constant.TradeType;
import com.jf.cloud.service.sysmanager.constant.UserConstant;
import com.jf.cloud.service.sysmanager.dao.IPubgClubService;
import com.jf.cloud.service.sysmanager.dao.IPubgExchangeOrderService;
import com.jf.cloud.service.sysmanager.dao.IPubgFinanceFlowDetailService;
import com.jf.cloud.service.sysmanager.dao.IPubgOperateLogService;
import com.jf.cloud.service.sysmanager.dao.IPubgTeamService;
import com.jf.cloud.service.sysmanager.dao.IPubgUserService;
import com.jf.cloud.service.sysmanager.entity.PubgClub;
import com.jf.cloud.service.sysmanager.entity.PubgExchangeOrder;
import com.jf.cloud.service.sysmanager.entity.PubgFinanceFlowDetail;
import com.jf.cloud.service.sysmanager.entity.PubgOperateLog;
import com.jf.cloud.service.sysmanager.entity.PubgTeam;
import com.jf.cloud.service.sysmanager.entity.PubgUser;


/**
 * 员工服务实现
 * 
 * @author 绝峰代码机1.0 创建时间：2018-03-31
 */
@Service("pubgExchangeOrderService")
public class PubgExchangeOrderServiceImpl extends BaseService<PubgExchangeOrder, Long> implements IPubgExchangeOrderService {

	/**
	 * 日志
	 */
	private static Log log = LogFactory.getLog(PubgExchangeOrderServiceImpl.class);

	/**
	 * JPA公共DAO
	 */
	@Resource
	private BaseDao baseDao;

	private RowMapper<PubgExchangeOrder> rowMapper = new BeanPropertyRowMapper<PubgExchangeOrder>(GenericsUtils.getSuperClassGenricType(this.getClass()));

	/**
	 * 员工服务
	 */
	@Resource
	private IPubgUserService pubgUserService;

	/**
	 * 俱乐部服务
	 */
	@Resource
	private IPubgClubService pubgClubService;

	@Resource
	private IPubgTeamService pubgTeamService;

	@Resource
	private IPubgFinanceFlowDetailService pubgFinanceFlowDetailService;

	@Resource
	private IPubgOperateLogService pubgOperateLogService;
	
	@Resource
	private SequenceHandler sequenceHandler;

	/**
	 * 根据主键查询员工
	 * 
	 * @author 绝峰代码机1.0 创建时间：2018-03-31
	 */
	public PubgExchangeOrder findPubgExchangeOrder(Long rowId) throws Exception {
		try {
			return this.baseDao.findObject("", rowMapper, rowId);
		} catch (Exception e) {
			throw new Exception("根据主键查询员工出错！", e);
		}
	}

	/**
	 * 根据查询条件获取员工列表
	 * 
	 * @author 绝峰代码机1.0 创建时间：2018-03-31
	 */
	public List<PubgExchangeOrder> findPubgExchangeOrderList(Condition qc) throws Exception {
		try {
			return this.baseDao.findList("", rowMapper);
		} catch (Exception e) {
			throw new Exception("根据查询条件获取员工列表出错！", e);
		}
	}

	/**
	 * 新增/修改员工
	 * 
	 * @author 绝峰代码机1.0 创建时间：2018-03-31
	 */
	@Transactional
	public PubgExchangeOrder saveOrUpdatePubgExchangeOrder(PubgExchangeOrder pubgExchangeOrder) throws Exception {
		try {
			return this.baseDao.saveAll(pubgExchangeOrder);
		} catch (Exception e) {
			throw new Exception("新增/修改员工出错！", e);
		}
	}

	/**
	 * app获取兑换记录列表
	 * 
	 * @author 朱建文 创建时间：2018年4月11日 下午1:58:07
	 */
	public List<Map<String, Object>> getExchageOrderList(OPaging<Map<String, Object>> page) throws Exception {
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		String sql = "SELECT ROW_ID rowId, GOODS_NAME goodsName, GOODS_PRICE goodsPrice, ";
		sql += " APPLY_TIME applyTime, CONVERSION_STATE state ";
		sql += " FROM pubg_exchange_order";
		sql += page.getWhereSQL(true);
		sql += page.getOrderBy(true);
        Paging<Map<String, Object>> pageTemp = this.baseDao.findObjectListMapByPage(sql, page, page.getParamList().toArray());
		dataList = pageTemp.getDataList();
		return dataList;
	}

	/**
	 * 兑换商品
	 * @author 高冬冬 2018年4月12日
	 */
	@Transactional
	@Override
	public void addExchangeOrder(PubgExchangeOrder pubgExchangeOrder) throws Exception {
		try {
			
			// 保存兑换商品订单
			pubgExchangeOrder.setOrderNo(sequenceHandler.getBizNo(SequenceHandler.EX));
			baseDao.saveAll(pubgExchangeOrder);
			if (pubgExchangeOrder.getUserRole() == UserConstant.USER_ROLE_10.getId().intValue()) {

				// 更新用户余额
				if (pubgExchangeOrder.getBalance() == null) {
					pubgExchangeOrder.setBalance(0d);
				}
				String updateSqlReturn = "UPDATE pubg_user SET BALANCE = IFNULL(BALANCE,0) - ? ";
				updateSqlReturn += " WHERE ROW_ID = ? AND IFNULL(BALANCE,0) >= ? AND IFNULL(BALANCE,0) = ? ";
				baseDao.update(updateSqlReturn, pubgExchangeOrder.getGoodsPrice(), 
						pubgExchangeOrder.getUserId(), pubgExchangeOrder.getGoodsPrice(), pubgExchangeOrder.getBalance());
				
				// 更新用户-战队 余额
				if (pubgExchangeOrder.getUserTeamBalance() == null) {
					pubgExchangeOrder.setUserTeamBalance(0d);
				}
				updateSqlReturn = "UPDATE pubg_user_team SET USER_TEAM_BALANCE = IFNULL(USER_TEAM_BALANCE,0) - ? ";
				updateSqlReturn += " WHERE USER_ID = ? AND TEAM_ID = ? AND CLUB_ID = ? AND IFNULL(USER_TEAM_BALANCE,0) >= ? AND IFNULL(USER_TEAM_BALANCE,0) = ? ";
				baseDao.update(updateSqlReturn, pubgExchangeOrder.getGoodsPrice(), pubgExchangeOrder.getUserId(), 
						pubgExchangeOrder.getTeamId(), pubgExchangeOrder.getClubId(), pubgExchangeOrder.getGoodsPrice(), pubgExchangeOrder.getUserTeamBalance());
				
				// 更新用户-俱乐部 余额
				if (pubgExchangeOrder.getUserClubBalance() == null) {
					pubgExchangeOrder.setUserClubBalance(0d);
				}
				updateSqlReturn = "UPDATE pubg_user_club SET USER_CLUB_BALANCE = IFNULL(USER_CLUB_BALANCE,0) - ? ";
				updateSqlReturn += " WHERE USER_ID = ? AND CLUB_ID = ? AND IFNULL(USER_CLUB_BALANCE,0) >= ? AND IFNULL(USER_CLUB_BALANCE,0) = ? ";
				baseDao.update(updateSqlReturn, pubgExchangeOrder.getGoodsPrice(), pubgExchangeOrder.getUserId(), 
						pubgExchangeOrder.getClubId(), pubgExchangeOrder.getGoodsPrice(), pubgExchangeOrder.getUserClubBalance());
				
			// 战队
			} else if (pubgExchangeOrder.getUserRole() == UserConstant.USER_ROLE_20.getId().intValue()) {
				
				// 更新战队余额
				if (pubgExchangeOrder.getTeamBalance() == null) {
					pubgExchangeOrder.setTeamBalance(0d);
				}
				String updateSql = "UPDATE pubg_team SET TEAM_BALANCE = IFNULL(TEAM_BALANCE,0) - ? ";
				updateSql += " WHERE ROW_ID = ? AND IFNULL(TEAM_BALANCE,0) >= ? AND IFNULL(TEAM_BALANCE,0) = ? ";
				baseDao.update(updateSql.toString(), pubgExchangeOrder.getGoodsPrice(), 
						pubgExchangeOrder.getTeamId(), pubgExchangeOrder.getGoodsPrice(), pubgExchangeOrder.getTeamBalance());
				
			// 俱乐部
			} else if (pubgExchangeOrder.getUserRole() == UserConstant.USER_ROLE_30.getId().intValue()) {
				// 更新俱乐部余额
				if (pubgExchangeOrder.getClubBalance() == null) {
					pubgExchangeOrder.setClubBalance(0d);
				}
				String updateSql = "UPDATE pubg_club SET CLUB_BALANCE = IFNULL(CLUB_BALANCE,0) - ? ";
				updateSql += " WHERE ROW_ID = ? AND IFNULL(CLUB_BALANCE,0) >= ? AND IFNULL(CLUB_BALANCE,0) = ? ";
				baseDao.update(updateSql.toString(), pubgExchangeOrder.getGoodsPrice(), 
						pubgExchangeOrder.getClubId(), pubgExchangeOrder.getGoodsPrice(), pubgExchangeOrder.getClubBalance());
			}
		} catch (Exception e) {
			throw new RuntimeException("兑换商品出错！", e);
		}
	}

	/**
	 * 修改商场物品兑换订单状态
	 * @author 高冬冬 2018年4月12日
	 * orderId:订单ID conversionState:更新状态 optId:操作人ID optAccount:操作人账号
	 * fromType:请求来源（manage:后台管理系统），app请求不传此参数
	 */
	@Transactional
	@Override
	public void updateOrderConversionState(PubgExchangeOrder pubgExchangeOrder, String conversionState, Long optId, String optAccount, String fromType) throws Exception {
		try {
			
			// 更新订单状态
			String updateSql = "UPDATE pubg_exchange_order SET CONVERSION_STATE=?, MANAGE_TIME=? WHERE ROW_ID=? AND CONVERSION_STATE='10'";
			baseDao.update(updateSql, conversionState, DateUtil.getCurrentDateTime(), pubgExchangeOrder.getRowId());
			PubgUser orderUser = pubgUserService.findByPK(pubgExchangeOrder.getUserId());//兑换商品用户
			
			//后台处理部长的兑换
			if ("manage".equals(fromType)) {
				if (orderUser.getUserRole() != UserConstant.USER_ROLE_30.getId().intValue()) {
					throw new RuntimeException("后台只能处理俱乐部的订单！");
				}
				
				// 同意
				if (PubgConstant.CONVERSION_STATE_20.equals(conversionState)) {
					
					// 
					PubgFinanceFlowDetail pubgFinanceFlowDetail = new PubgFinanceFlowDetail();
					pubgFinanceFlowDetail.setCreateTime(DateUtil.getCurrentDateTime());
					pubgFinanceFlowDetail.setTradeTypeId(TradeType.EX_ORDER_SUCCESS.key());
					pubgFinanceFlowDetail.setTradeTypeName(TradeType.EX_ORDER_SUCCESS.value());
					pubgFinanceFlowDetail.setInOutFlag(PubgConstant.FINANCE_FLOW_OUT);
					pubgFinanceFlowDetail.setClubId(pubgExchangeOrder.getClubId());
					pubgFinanceFlowDetail.setClubName(pubgExchangeOrder.getClubName());
					pubgFinanceFlowDetail.setTradeMoney(pubgExchangeOrder.getGoodsPrice());//客户端传递的变化鸡蛋数量
					pubgFinanceFlowDetail.setTradeMoneyAfter(pubgExchangeOrder.getClubBalance());//更新后的鸡蛋数量
					pubgFinanceFlowDetailService.saveOrUpdatePubgFinanceFlowDetail(pubgFinanceFlowDetail);
					
				// 已撤销
				} else if (PubgConstant.CONVERSION_STATE_30.equals(conversionState)) {
					PubgClub pubgClub = pubgClubService.findByPK(pubgExchangeOrder.getClubId());//俱乐部
					String updateSqlReturn = "UPDATE pubg_club SET CLUB_BALANCE = IFNULL(CLUB_BALANCE,0) + ? WHERE ROW_ID = ? ";
					baseDao.update(updateSqlReturn, pubgExchangeOrder.getGoodsPrice(), pubgClub.getRowId());
				}
				
			} else {
				
				// 处理完成
				if (PubgConstant.CONVERSION_STATE_20.equals(conversionState)) {
					
					PubgUser loginUser = pubgUserService.findByPK(optId);//当前登陆用户
					if (loginUser.getUserRole() == UserConstant.USER_ROLE_30.getId().intValue()
							&& orderUser.getUserRole() == UserConstant.USER_ROLE_20.getId().intValue()) {

						// 更新俱乐部余额（需要把鸡蛋给俱乐部加上）
						updateSql = "UPDATE pubg_club SET CLUB_BALANCE = IFNULL(CLUB_BALANCE,0) + ? ";
						updateSql += " WHERE ROW_ID = ? AND CLUB_BALANCE = ?";
						this.baseDao.update(updateSql, pubgExchangeOrder.getGoodsPrice(), 
								pubgExchangeOrder.getClubId(), pubgExchangeOrder.getClubBalance());
						
						// 插入战队的流水   减
						PubgFinanceFlowDetail teamFlowDetail = new PubgFinanceFlowDetail();
						teamFlowDetail.setCreateTime(DateUtil.getCurrentDateTime());
						teamFlowDetail.setTradeTypeId(TradeType.EX_ORDER_SUCCESS.key());
						teamFlowDetail.setTradeTypeName(TradeType.EX_ORDER_SUCCESS.value());
						teamFlowDetail.setInOutFlag(PubgConstant.FINANCE_FLOW_OUT);
						teamFlowDetail.setClubId(pubgExchangeOrder.getClubId());
						teamFlowDetail.setClubName(pubgExchangeOrder.getClubName());
						teamFlowDetail.setTeamId(pubgExchangeOrder.getTeamId());
						teamFlowDetail.setTeamName(pubgExchangeOrder.getTeamName());
						teamFlowDetail.setTradeMoney(pubgExchangeOrder.getGoodsPrice() * -1);//客户端传递的变化鸡蛋数量
						teamFlowDetail.setTradeMoneyAfter(pubgExchangeOrder.getTeamBalance());//更新后的鸡蛋数量
						teamFlowDetail.setRelationOrderNo(pubgExchangeOrder.getOrderNo());
						pubgFinanceFlowDetailService.saveOrUpdatePubgFinanceFlowDetail(teamFlowDetail);
						
						// 插入俱乐部的流水   加
						PubgFinanceFlowDetail clubFlowDetail = new PubgFinanceFlowDetail();
						clubFlowDetail.setCreateTime(DateUtil.getCurrentDateTime());
						clubFlowDetail.setTradeTypeId(TradeType.EX_ORDER_SUCCESS.key());
						clubFlowDetail.setTradeTypeName(TradeType.EX_ORDER_SUCCESS.value());
						clubFlowDetail.setInOutFlag(PubgConstant.FINANCE_FLOW_IN);
						clubFlowDetail.setClubId(pubgExchangeOrder.getClubId());
						clubFlowDetail.setClubName(pubgExchangeOrder.getClubName());
						clubFlowDetail.setTradeMoney(pubgExchangeOrder.getGoodsPrice());//客户端传递的变化鸡蛋数量
						clubFlowDetail.setTradeMoneyAfter(pubgExchangeOrder.getClubBalance() + pubgExchangeOrder.getGoodsPrice());//更新后的鸡蛋数量
						clubFlowDetail.setRelationOrderNo(pubgExchangeOrder.getOrderNo());
						pubgFinanceFlowDetailService.saveOrUpdatePubgFinanceFlowDetail(clubFlowDetail);
						
					} else if (loginUser.getUserRole() == UserConstant.USER_ROLE_20.getId().intValue() 
							&& orderUser.getUserRole() == UserConstant.USER_ROLE_10.getId().intValue()) {

						// 更新战队余额（需要把鸡蛋给战队加上）
						updateSql = "UPDATE pubg_team SET TEAM_BALANCE = IFNULL(TEAM_BALANCE,0) + ? ";
						updateSql += " WHERE ROW_ID = ? AND TEAM_BALANCE = ?";
						this.baseDao.update(updateSql, pubgExchangeOrder.getGoodsPrice(), 
								pubgExchangeOrder.getTeamId(), pubgExchangeOrder.getTeamBalance());
						
						// 插入队员的流水   减
						PubgFinanceFlowDetail memberFlowDetail = new PubgFinanceFlowDetail();
						memberFlowDetail.setCreateTime(DateUtil.getCurrentDateTime());
						memberFlowDetail.setTradeTypeId(TradeType.EX_ORDER_SUCCESS.key());
						memberFlowDetail.setTradeTypeName(TradeType.EX_ORDER_SUCCESS.value());
						memberFlowDetail.setInOutFlag(PubgConstant.FINANCE_FLOW_OUT);
						memberFlowDetail.setClubId(pubgExchangeOrder.getClubId());
						memberFlowDetail.setClubName(pubgExchangeOrder.getClubName());
						memberFlowDetail.setTeamId(pubgExchangeOrder.getTeamId());
						memberFlowDetail.setTeamName(pubgExchangeOrder.getTeamName());
						memberFlowDetail.setUserId(pubgExchangeOrder.getUserId());
						memberFlowDetail.setUserAccount(pubgExchangeOrder.getUserAccount());
						memberFlowDetail.setTradeMoney(pubgExchangeOrder.getGoodsPrice() * -1);//客户端传递的变化鸡蛋数量
						memberFlowDetail.setTradeMoneyAfter(pubgExchangeOrder.getBalance());//更新后的鸡蛋数量
						memberFlowDetail.setRelationOrderNo(pubgExchangeOrder.getOrderNo());
						pubgFinanceFlowDetailService.saveOrUpdatePubgFinanceFlowDetail(memberFlowDetail);
						
						// 插入战队的流水   加
						PubgFinanceFlowDetail teamFlowDetail = new PubgFinanceFlowDetail();
						teamFlowDetail.setCreateTime(DateUtil.getCurrentDateTime());
						teamFlowDetail.setTradeTypeId(TradeType.EX_ORDER_SUCCESS.key());
						teamFlowDetail.setTradeTypeName(TradeType.EX_ORDER_SUCCESS.value());
						teamFlowDetail.setInOutFlag(PubgConstant.FINANCE_FLOW_IN);
						teamFlowDetail.setClubId(pubgExchangeOrder.getClubId());
						teamFlowDetail.setClubName(pubgExchangeOrder.getClubName());
						teamFlowDetail.setTeamId(pubgExchangeOrder.getTeamId());
						teamFlowDetail.setTeamName(pubgExchangeOrder.getTeamName());
						teamFlowDetail.setTradeMoney(pubgExchangeOrder.getGoodsPrice()); //客户端传递的变化鸡蛋数量
						teamFlowDetail.setTradeMoneyAfter(pubgExchangeOrder.getTeamBalance() + pubgExchangeOrder.getGoodsPrice());//更新后的鸡蛋数量
						teamFlowDetail.setRelationOrderNo(pubgExchangeOrder.getOrderNo());
						pubgFinanceFlowDetailService.saveOrUpdatePubgFinanceFlowDetail(teamFlowDetail);
					}
					
				// 已撤销
				} else if (PubgConstant.CONVERSION_STATE_30.equals(conversionState)) {
					
					PubgUser loginUser = pubgUserService.findByPK(optId);//当前登陆用户
					if (loginUser.getUserRole() == UserConstant.USER_ROLE_30.getId().intValue()) {
						if (orderUser.getUserRole() == UserConstant.USER_ROLE_20.getId().intValue()) {
							PubgTeam pubgTeam = pubgTeamService.findByPK(pubgExchangeOrder.getTeamId());//战队
							String updateSqlReturn = "UPDATE pubg_team SET TEAM_BALANCE = IFNULL(TEAM_BALANCE,0) + ? WHERE ROW_ID = ? ";
							baseDao.update(updateSqlReturn, pubgExchangeOrder.getGoodsPrice(), pubgTeam.getRowId());
						}
						if (orderUser.getUserRole() == UserConstant.USER_ROLE_10.getId().intValue()) {
						}
					} else if (loginUser.getUserRole() == UserConstant.USER_ROLE_20.getId().intValue() && orderUser.getUserRole() == UserConstant.USER_ROLE_10.getId().intValue()) {
						
						// 更新用户余额
						String updateSqlReturn = "UPDATE pubg_user SET BALANCE = IFNULL(BALANCE,0) + ? WHERE ROW_ID = ? ";
						baseDao.update(updateSqlReturn, pubgExchangeOrder.getGoodsPrice(), orderUser.getRowId());
						
						// 更新队员-战队余额
						updateSqlReturn = "UPDATE pubg_user_team SET USER_TEAM_BALANCE = IFNULL(USER_TEAM_BALANCE,0) + ? WHERE USER_ID = ? AND TEAM_ID = ? AND CLUB_ID = ? ";
						baseDao.update(updateSqlReturn, pubgExchangeOrder.getGoodsPrice(), orderUser.getRowId(), pubgExchangeOrder.getTeamId(), pubgExchangeOrder.getClubId());
						
						// 更新队员-俱乐部余额
						updateSqlReturn = "UPDATE pubg_user_club SET USER_CLUB_BALANCE = IFNULL(USER_CLUB_BALANCE,0) + ? WHERE USER_ID = ? AND CLUB_ID = ? ";
						baseDao.update(updateSqlReturn, pubgExchangeOrder.getGoodsPrice(), orderUser.getRowId(), pubgExchangeOrder.getClubId());
					}
				}
			}
			
			//构建操作日志对象 BEGIN
			PubgOperateLog pubgOperateLog = new PubgOperateLog();
			pubgOperateLog.setClubId(pubgExchangeOrder.getClubId());
			pubgOperateLog.setClubName(pubgExchangeOrder.getClubName());
			pubgOperateLog.setTeamId(pubgExchangeOrder.getTeamId());
			pubgOperateLog.setTeamName(pubgExchangeOrder.getTeamName());
			pubgOperateLog.setUserId(pubgExchangeOrder.getUserId());
			pubgOperateLog.setUserAccount(pubgExchangeOrder.getUserAccount());
			pubgOperateLog.setOptId(optId);
			pubgOperateLog.setOptName(optAccount);
			pubgOperateLog.setOptTime(DateUtil.getCurrentDateTime());
			pubgOperateLog.setContent("兑换订单处理完成，操作人：" + optAccount);
			pubgOperateLog.setOptType(TradeType.EX_ORDER_SUCCESS.key());
			if (PubgConstant.CONVERSION_STATE_30.equals(pubgExchangeOrder.getConversionState())) {
				pubgOperateLog.setContent("兑换订单撤销兑换，操作人：" + optAccount);
				pubgOperateLog.setOptType(TradeType.EX_ORDER_CANCEL.key());
			}
			pubgOperateLogService.saveOrUpdatePubgOperateLog(pubgOperateLog);
		} catch (Exception e) {
			throw new RuntimeException("修改商场物品兑换订单状态出错！", e);
		}
	}
}
